import 'package:redux/redux.dart';
import '../models/social_post_entity.dart';
import '../models/post_comment_entity.dart';
import '../data/default_social_data.dart';

/// Redux社交动态状态
class ReduxSocialState {
  final List<SocialPostEntity> postCollection;
  final List<PostCommentEntity> commentCollection;

  const ReduxSocialState({
    this.postCollection = const [],
    this.commentCollection = const [],
  });

  ReduxSocialState copyWith({
    List<SocialPostEntity>? postCollection,
    List<PostCommentEntity>? commentCollection,
  }) {
    return ReduxSocialState(
      postCollection: postCollection ?? this.postCollection,
      commentCollection: commentCollection ?? this.commentCollection,
    );
  }
}

/// Redux社交动态动作
abstract class ReduxSocialAction {}

class InitializeSocialDataAction extends ReduxSocialAction {
  final List<SocialPostEntity> postList;
  final List<PostCommentEntity> commentList;
  InitializeSocialDataAction({
    required this.postList,
    required this.commentList,
  });
}

class AddNewPostAction extends ReduxSocialAction {
  final SocialPostEntity newPost;
  AddNewPostAction(this.newPost);
}

class LikePostAction extends ReduxSocialAction {
  final String postId;
  final String userId;
  LikePostAction({required this.postId, required this.userId});
}

class UnlikePostAction extends ReduxSocialAction {
  final String postId;
  final String userId;
  UnlikePostAction({required this.postId, required this.userId});
}

class AddCommentAction extends ReduxSocialAction {
  final PostCommentEntity newComment;
  AddCommentAction(this.newComment);
}

class DeletePostAction extends ReduxSocialAction {
  final String postId;
  DeletePostAction(this.postId);
}

class DeleteCommentAction extends ReduxSocialAction {
  final String commentId;
  DeleteCommentAction(this.commentId);
}

/// Redux社交动态Reducer
ReduxSocialState socialReducer(ReduxSocialState state, dynamic action) {
  if (action is InitializeSocialDataAction) {
    return state.copyWith(
      postCollection: action.postList,
      commentCollection: action.commentList,
    );
  }

  if (action is AddNewPostAction) {
    final updatedPosts = List<SocialPostEntity>.from(state.postCollection)
      ..insert(0, action.newPost); // 新动态插入到顶部
    return state.copyWith(postCollection: updatedPosts);
  }

  if (action is LikePostAction) {
    final updatedPosts =
        state.postCollection.map((post) {
          if (post.postId == action.postId) {
            if (!post.likedUserIds.contains(action.userId)) {
              final updatedLikedUsers = List<String>.from(post.likedUserIds)
                ..add(action.userId);
              return post.copyWith(
                likeCount: post.likeCount + 1,
                likedUserIds: updatedLikedUsers,
              );
            }
          }
          return post;
        }).toList();
    return state.copyWith(postCollection: updatedPosts);
  }

  if (action is UnlikePostAction) {
    final updatedPosts =
        state.postCollection.map((post) {
          if (post.postId == action.postId) {
            if (post.likedUserIds.contains(action.userId)) {
              final updatedLikedUsers = List<String>.from(post.likedUserIds)
                ..remove(action.userId);
              return post.copyWith(
                likeCount: post.likeCount - 1,
                likedUserIds: updatedLikedUsers,
              );
            }
          }
          return post;
        }).toList();
    return state.copyWith(postCollection: updatedPosts);
  }

  if (action is AddCommentAction) {
    final updatedComments = List<PostCommentEntity>.from(
      state.commentCollection,
    )..add(action.newComment);

    // 更新对应动态的评论数
    final updatedPosts =
        state.postCollection.map((post) {
          if (post.postId == action.newComment.postId) {
            return post.copyWith(commentCount: post.commentCount + 1);
          }
          return post;
        }).toList();

    return state.copyWith(
      postCollection: updatedPosts,
      commentCollection: updatedComments,
    );
  }

  if (action is DeletePostAction) {
    final updatedPosts =
        state.postCollection
            .where((post) => post.postId != action.postId)
            .toList();
    final updatedComments =
        state.commentCollection
            .where((comment) => comment.postId != action.postId)
            .toList();
    return state.copyWith(
      postCollection: updatedPosts,
      commentCollection: updatedComments,
    );
  }

  if (action is DeleteCommentAction) {
    final updatedComments =
        state.commentCollection
            .where((comment) => comment.commentId != action.commentId)
            .toList();

    // 更新对应动态的评论数
    final commentToDelete =
        state.commentCollection
            .where((comment) => comment.commentId == action.commentId)
            .toList();

    if (commentToDelete.isNotEmpty) {
      final postId = commentToDelete.first.postId;
      final updatedPosts =
          state.postCollection.map((post) {
            if (post.postId == postId) {
              return post.copyWith(commentCount: post.commentCount - 1);
            }
            return post;
          }).toList();

      return state.copyWith(
        postCollection: updatedPosts,
        commentCollection: updatedComments,
      );
    }

    return state.copyWith(commentCollection: updatedComments);
  }

  return state;
}

/// Redux社交动态服务
class ReduxSocialManager {
  static final ReduxSocialManager _instance = ReduxSocialManager._internal();
  factory ReduxSocialManager() => _instance;
  ReduxSocialManager._internal();

  Store<dynamic>? _store;

  void initialize(Store<dynamic> store) {
    _store = store;
  }

  Store<dynamic> get store {
    if (_store == null) throw Exception('Social service not initialized');
    return _store!;
  }

  void initializeSocialData() {
    final socialData = DefaultSocialDataCollection.defaultSocialData;
    store.dispatch(
      InitializeSocialDataAction(
        postList: socialData.posts,
        commentList: socialData.comments,
      ),
    );
  }

  List<SocialPostEntity> getAllPosts() =>
      List.from(store.state.socialState.postCollection);

  List<PostCommentEntity> getAllComments() =>
      List.from(store.state.socialState.commentCollection);

  List<PostCommentEntity> getCommentsByPostId(String postId) {
    return store.state.socialState.commentCollection
        .where((comment) => comment.postId == postId)
        .toList();
  }

  SocialPostEntity? getPostById(String postId) {
    try {
      return store.state.socialState.postCollection.firstWhere(
        (post) => post.postId == postId,
      );
    } catch (e) {
      return null;
    }
  }

  bool isPostLikedByUser(String postId, String userId) {
    final post = getPostById(postId);
    return post?.likedUserIds.contains(userId) ?? false;
  }

  int getPostLikeCount(String postId) {
    final post = getPostById(postId);
    return post?.likeCount ?? 0;
  }

  int getPostCommentCount(String postId) {
    final post = getPostById(postId);
    return post?.commentCount ?? 0;
  }

  // 获取用户所有动态的点赞数总和
  int getUserTotalLikes(String userId) {
    final userPosts =
        store.state.socialState.postCollection
            .where((post) => post.authorId == userId)
            .toList();

    int totalLikes = 0;
    for (final post in userPosts) {
      totalLikes += post.likeCount as int;
    }

    return totalLikes;
  }

  Future<bool> publishPost(SocialPostEntity newPost) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));
      store.dispatch(AddNewPostAction(newPost));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> likePost(String postId, String userId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(LikePostAction(postId: postId, userId: userId));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> unlikePost(String postId, String userId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(UnlikePostAction(postId: postId, userId: userId));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> addComment(PostCommentEntity newComment) async {
    try {
      await Future.delayed(const Duration(milliseconds: 400));
      store.dispatch(AddCommentAction(newComment));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> deletePost(String postId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(DeletePostAction(postId));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> deleteComment(String commentId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));
      store.dispatch(DeleteCommentAction(commentId));
      return true;
    } catch (e) {
      return false;
    }
  }

  int getTotalPostCount() => store.state.socialState.postCollection.length;
  int getTotalCommentCount() =>
      store.state.socialState.commentCollection.length;

  List<SocialPostEntity> getPostsSortedByTime() {
    final posts = List<SocialPostEntity>.from(
      store.state.socialState.postCollection,
    );
    posts.sort((a, b) => b.publishTime.compareTo(a.publishTime));
    return posts;
  }
}
